package com.boxfishedu.conf;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;

/**
 * Created by lzx on 16/7/6.
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.boxfishedu.second",entityManagerFactoryRef = "secondEntityManagerFactoryBean",
transactionManagerRef = "secondTransactionManager")
@EnableTransactionManagement
public class SecondRepositoryConf {

    @Autowired
    JpaProperties jpaProperties;

    @Autowired
    @Qualifier(value = "secondDataSource")
    DataSource secondDataSource;

    @Bean(name = "secondEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory(EntityManagerFactoryBuilder builder){
        return localContainerEntityManagerFactoryBean(builder).getObject();
    }

    @Bean(name = "secondEntityManagerFactoryBean")
    public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean(EntityManagerFactoryBuilder builder){
        return builder.dataSource(secondDataSource)
                .packages("com.boxfishedu.second")
                .persistenceUnit("secondPersisUnit")
                .properties(jpaProperties.getHibernateProperties(secondDataSource))
                .build();
    }

    @Bean(name = "secondTransactionManager")
    public PlatformTransactionManager jpaTransactionManager(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(entityManagerFactory(builder));
    }

}
